/**
 * Bestpay.com.cn Inc.
 * Copyright (c) 2011-2018 All Rights Reserved.
 */
package com.sgzn.sgpay.web.controller.base;

import com.sgzn.sgpay.enums.AppName;
import com.sgzn.sgpay.model.request.SgsSessionQueryRequest;
import com.sgzn.sgpay.model.response.SgsResultResponse;
import com.sgzn.sgpay.persistence.domain.TLoginSession;
import com.sgzn.sgpay.service.SgsSessionQueryService;
import com.sgzn.sgpay.util.SerialNoUtil;
import com.sgzn.sgpay.util.TranslateUtil;
import com.sgzn.sgpay.web.request.Impl.UserBaseRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 用户接口基础控制器
 * @author zhongzhongyong
 * @version Id: UserBaseController.java, v 0.1 2018/6/19 23:38 zhongzhongyong Exp $$
 */
@Slf4j
public abstract class UserBaseController {

    @Autowired
    private SgsSessionQueryService sgsSessionQueryService;

    /**
     * 设置用户信息
     * @param request
     */
    public void setUserInfo(UserBaseRequest request){
        TLoginSession session = getLoginSession(request.getLoginToken());
        if(session != null){
            request.setOpenId(session.getOpenId());
            request.setUserId(session.getUserId());
        }else{
            log.error("用户未登录");
        }
    }

    /**
     * 获取用户会话
     * 若loginToken有效
     * @param loginToken
     * @return
     */
    private TLoginSession getLoginSession(String loginToken){
        SgsSessionQueryRequest request = new SgsSessionQueryRequest();
        request.setLoginToken(loginToken);
        request.setInitiationID(SerialNoUtil.generateSerialNo(AppName.SGW));
        SgsResultResponse<TLoginSession> sgsResp = sgsSessionQueryService.queryUserSession(request);
        if(TranslateUtil.isSuccessAbs(sgsResp.getErrorCode()) && sgsResp.getResult() != null){
            return sgsResp.getResult();
        }else{
            return null;
        }
    }

}